<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="权限等级" width="80">
        <template slot-scope="{row}">
          <span>{{ row.permission }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作规则" width="240">
        <template slot-scope="{row}">
          <span>{{ row.rule }}</span>
        </template>
      </el-table-column>

      <el-table-column width="380" align="center" label="权限描述">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" :disabled="initialRole==='admin'?false:true" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="success" @click="dialogTableVisible = true, handleModifyStatus(row)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog title="用户列表" :visible.sync="dialogTableVisible">
      <el-table
        :key="tableKey"
        :data="looklist"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="用户名" width="190">
          <template slot-scope="{row}">
            <span>{{ row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="权限等级" width="350">
          <template slot-scope="{row}">
            <span>{{ row.profile__roles }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogTableVisible = false">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="Id" prop="id" label-width="140">
          <el-input v-model="temp.id" :disabled="true" />
        </el-form-item>
        <el-form-item label="操作规则" prop="rule" label-width="140">
          <el-input v-model="temp.rule" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description" label-width="140">
          <el-input v-model="temp.description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus===updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import { getPermission, editPermission, getUerByPermission } from '@/api/role'
import { getRole } from '@/api/user'

export default {
  name: 'Permission',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      looklist: null,
      total: 0,
      listLoading: true,
      listQuery: {
        token: getToken(),
        page: 1,
        limit: 30,
        id: undefined,
        rule: undefined,
        permission: undefined,
        description: undefined
      },
      initialRole: '3',
      roleOptions: ['admin', 1, 2, 3],
      superOptions: ['True', 'False'],
      onlineOptions: [0, 1],
      activeOptions: [0, 1],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        rule: undefined,
        permission: undefined,
        description: undefined
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        role: [{ required: true }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.getNowRole()
  },
  methods: {
    getNowRole() {
      getRole(getToken()).then(response => {
        this.initialRole = response.role
        console.log(this.initialRole)
      })
    },
    getList() {
      this.listLoading = true
      getPermission(getToken()).then(response => {
        this.list = response.data
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row) {
      getUerByPermission(getToken(), row.permission).then(response => {
        const code = response
        this.looklist = response.data
        if (code === 2000) {
          this.$notify({
            title: 'Success',
            message: response.message,
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'UnSuccess',
            message: response.message,
            type: 'error',
            duration: 1000
          })
        }
      })
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    restCreateTemp() {
      this.creatTemp = {
        username: '',
        password: '',
        checkPass: '',
        email: '',
        role: '',
        introduction: ''
      }
    },
    handleCreate() {
      this.restCreateTemp()
      this.dialogStatus = 'create'
      this.dialogFormCreateVisible = true
      // this.$nextTick(() => {
      //   this.$refs['creatTempForm'].clearValidate()
      // })
    },
    resetCreateForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          editPermission(getToken(), tempData).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            const code = response.code
            if (code === 2000) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: response.message,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'UnSuccess',
                message: response.message,
                type: 'error',
                duration: 1000
              })
            }
          })
        }
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
